package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计
     * */
    @Override
    public TurnoverReportVO turnoverStatistic(LocalDate begin, LocalDate end) {
        // 构造日期列表
        List<LocalDate> datalist = getDateList(begin, end);
        // 查询每天的订单营业额
        List<Double> turnoverList = new ArrayList<Double>();
        datalist.forEach(date->{
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN)); // 一天开始的时间
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX)); // 一天结束的时间
            Double turnover = ordersMapper.sumByMap(map);
            turnover = turnover == null ? 0 : turnover;
            turnoverList.add(turnover);
        });

        //new TurnoverReportVO();
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(datalist,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }
    /**
     * 用户统计
     * */
    @Override
    public UserReportVO userStatistic(LocalDate begin, LocalDate end) {
        // 构造日期列表
        List<LocalDate> datalist = getDateList(begin,end);
        //
        List<Long> newUserList = new ArrayList<Long>();
        List<Long> totalUserList = new ArrayList<Long>();
        datalist.forEach(date->{
            // 查询新增用户
            Map map = new HashMap();
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN)); // 一天开始的时间
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX)); // 一天结束的时间
            Long newUser = userMapper.countByMap(map);
//            log.info("{}日新增:{}",date,newUser);
            newUserList.add(newUser);
            map.put("beginTime", null);
            Long totalUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);
        });
        return UserReportVO.builder()
                .dateList(StringUtils.join(datalist,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }
    /**
     * 订单统计
     * */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        // 日期列表
        List<LocalDate> datelist = getDateList(begin,end);
        List<Integer> completedCountList = new ArrayList<Integer>();
        List<Integer> countList = new ArrayList<Integer>();
        Integer totalCount = 0;
        Integer totalCompletedCount = 0;
        for (LocalDate date : datelist) {
            Map map = new HashMap();
            // 获取每日总订单列表数（根据下单时间）
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN)); // 一天开始的时间
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX)); // 一天结束的时间
            Integer count = ordersMapper.countByMap(map);
            countList.add(count);
            // 获取每日有效订单列表数（根据下单时间，且状态已完成的）
            map.put("status", Orders.COMPLETED);
            Integer completedCount = ordersMapper.countByMap(map);
            completedCountList.add(completedCount);
            // 获取区间订单总数（）
            totalCount = totalCount+count;
            // 获取区间有效订单数
            totalCompletedCount = totalCompletedCount+completedCount;
        }
        // 计算完成率
        Double rate = 0.0;
        if (totalCount != 0){
            rate = (totalCompletedCount+0.0) / totalCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(datelist,","))
                .orderCountList(StringUtils.join(countList, ","))
                .validOrderCountList(StringUtils.join(completedCountList, ","))
                .totalOrderCount(totalCount)
                .validOrderCount(totalCompletedCount)
                .orderCompletionRate(rate)
                .build();
    }
    /**
     * 销量统计
     * */
    @Override
    public SalesTop10ReportVO top(LocalDate begin, LocalDate end) {
        // nameList，商品名称列表
        List<String> nameList = new ArrayList<>();
        List<BigDecimal> numberList = new ArrayList<>();
        // 查询，根据时间，查询orders和order_detail表
        Map map = new HashMap();
        // 获取每日总订单列表数（根据下单时间）
        map.put("status", Orders.COMPLETED);
        map.put("beginTime", LocalDateTime.of(begin, LocalTime.MIN)); // begin这一天开始的时间
        map.put("endTime", LocalDateTime.of(end, LocalTime.MAX)); // 一天结束的时间
        List<Map> list = ordersMapper.top(map);
        for (Map m : list) {
            // 每个map中存放两对数据（name：菜品名）（num:份数）
            nameList.add((String) m.get("name"));
            numberList.add((BigDecimal)m.get("num"));
        }
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }
    /**
     * 报表导出
     * */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 1 查询数据库获取营业数据，最近30天的数据
        // 1.1 查询概览数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        // 2 将数据写入表格
        // 2.1 获取模板文件输入流
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            // 2.2 创建excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(in);
            // 2.3 填充概览数据数据
            // 时间
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            // 获取第二行第二个单元格写入时间
            sheet1.getRow(1).getCell(1).setCellValue("时间："+ dateBegin+"至"+dateEnd);
            XSSFRow row3 = sheet1.getRow(3); // 获取第4行
            row3.getCell(2).setCellValue(businessData.getTurnover()); // 写入营业额
            row3.getCell(4).setCellValue(businessData.getOrderCompletionRate()); // 写入订单完成率
            row3.getCell(6).setCellValue(businessData.getNewUsers()); // 写入新增用户数
            XSSFRow row4 = sheet1.getRow(4);
            row4.getCell(2).setCellValue(businessData.getValidOrderCount()); // 写入有效订单数
            row4.getCell(4).setCellValue(businessData.getUnitPrice());  // 平均客单价
            // 2.4 填充明细数据
            for (int i = 0; i < 30; i++) {
                // 算一天的明细数据
                LocalDate date = dateBegin.plusDays(i);
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                XSSFRow row = sheet1.getRow(7+i); // 获取第7+i行
                row.getCell(1).setCellValue(date.toString()); // 日期
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            // 3 将表格文件通过输出流下载到浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        // 构造日期列表
        List<LocalDate> datalist = new ArrayList<LocalDate>();
        while (!begin.isAfter(end)) {
            datalist.add(begin);
            begin = begin.plusDays(1);
        }
        return datalist;
    }
}
